package network;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;

import util.MD5Converter;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class NetworkHandler extends IntentService {
	private static NetworkHandler instance;
	private AstroClient client;
	private PropertyChangeSupport pcs;
	private boolean useFakeServer;
	
	public static NetworkHandler instance() {
		if(instance==null){
			instance = new NetworkHandler();
			return instance;
		} else {
			return instance;
		}
	}
	
	public void addObserver(PropertyChangeListener observer){
		pcs.addPropertyChangeListener(observer);
	}
	
	private NetworkHandler(){
		super("Network Handler.");
		useFakeServer = false;
		client = new AstroClient();
		pcs = new PropertyChangeSupport(this);
	}
	
	public boolean connect(String hostname, int portNumber, String password){
		useFakeServer = false;
		pcs = new PropertyChangeSupport(this);
		if(client == null){
			client = new AstroClient();
			return client.connect(hostname, portNumber, pcs, password);
		}
		else {
			return client.connect(hostname, portNumber, pcs, password);
		}
	}
	
	public ArrayList<String> getAllLogEvents(){
		return client.getLatestLog();
	}	
	
	public ArrayList<String> getPortFolios(){
		return null;
	}
	
	public Long getPortFolioValue(){
		return client.getPortfolioValue();
	}
	
	public int getSellValue(){
		return 0;
	}
	
	public int getBuyValue(){
		return 0;
	}

	public Boolean disconnect() {
		if(!useFakeServer){
			return client.disconnect();
		} else {
			return true;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		
	}
	
	public boolean isFakeServer(){
		return useFakeServer;
	}

	public void fakeServer() {
		useFakeServer = true;
	}

	public boolean isAuthenticated() {
		return client.isAuthenticated();
	}

}
